package com.taotao.cart.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.taotao.cart.pojo.Cart;
import com.taotao.cart.pojo.User;
import com.taotao.cart.service.CartService;
import com.taotao.cart.service.CookieCartService;
import com.taotao.cart.threadlocal.UserThreadLocal;

@Controller
@RequestMapping("cart")
public class CartController {

	@Autowired
	private CartService cartService;

	@Autowired
	private CookieCartService cookieCartService;

	@GetMapping("{itemId}")
	public String toCart(@PathVariable("itemId") Long itemId, HttpServletRequest request,
			HttpServletResponse response) {

		// 获取用户信息
		User user = UserThreadLocal.get();
		if (user == null) {
			// 未登陆状态的购物车
			this.cookieCartService.saveCart(itemId, request, response);
		} else {
			// 登陆状态的购物车
			this.cartService.saveCart(itemId, user.getId());
		}
		return "redirect:/cart/list.html";
	}

	@GetMapping("list")
	public String queryCarts(Model model, HttpServletRequest request) {

		List<Cart> cartList = null;
		// 获取用户信息
		User user = UserThreadLocal.get();
		if (user == null) {
			// 未登陆状态的购物车
			cartList = this.cookieCartService.queryCarts(request);
		} else {
			// 登陆状态的购物车
			cartList = this.cartService.queryCarts(user.getId());
		}
		model.addAttribute("cartList", cartList);
		return "cart";
	}

	@PostMapping("update/num/{itemId}/{num}")
	public String updateNum(@PathVariable("itemId") Long itemId, @PathVariable("num") Integer num,
			HttpServletRequest request, HttpServletResponse response) {

		// 获取用户信息
		User user = UserThreadLocal.get();
		if (user == null) {
			// 未登陆状态的购物车
			this.cookieCartService.updateNum(itemId, num, request, response);
		} else {
			// 登陆状态的购物车
			this.cartService.updateNum(itemId, user.getId(), num);
		}

		return "redirect:/cart/list.html";
	}

	@GetMapping("delete/{itemId}")
	public String deleteCart(@PathVariable("itemId") Long itemId, HttpServletRequest request,
			HttpServletResponse response) {
		// 获取用户信息
		User user = UserThreadLocal.get();
		if (user == null) {
			// 未登陆状态的购物车
			this.cookieCartService.deleteCart(itemId, request, response);
		} else {
			// 登陆状态的购物车
			this.cartService.deleteCart(itemId, user.getId());
		}
		return "redirect:/cart/list.html";
	}
}
